<?php
class LoadGraph{

	protected static $cores;

	public static function getNumberOfProcessorCores(){
		if( self::$cores === NULL ){
			exec( 'cat /proc/cpuinfo | grep processor | wc -l', $processors );
			self::$cores = (integer) array_shift( $processors );
		}
		return self::$cores;
	}

	public static function renderLoadTendency(){
		$loads		= sys_getloadavg();
		$max		= max( $loads );
		$part2		= $loads[2] / $max;
		$part1		= max( 0, ( $loads[1] / $max ) - $part2 );
		$part0		= max( 0, ( $loads[0] / $max ) - $part2 - $part1 );
		$bar2		= UI_HTML_Tag::create( 'div', "", array(
			'class'		=> 'bar bar-success',
			'style'		=> 'width: '.( round( $part2 * 100, 3 ) ).'%'
		) );
		$bar1		= UI_HTML_Tag::create( 'div', "", array(
			'class'		=> 'bar bar-warning',
			'style'		=> 'width: '.( round( $part1 * 100, 3 ) ).'%'
		) );
		$bar0		= UI_HTML_Tag::create( 'div', "", array(
			'class'		=> 'bar bar-danger',
			'style'		=> 'width: '.( round( $part0 * 100, 3 ) ).'%'
		) );
		return UI_HTML_Tag::create( 'div', $bar2.$bar1.$bar0, array( 'class' => 'progress' ) );
	}

	public static function renderLoadIndicator(){
		$loads			= sys_getloadavg();
		$load0Relative	= 1 / ( 1 + $loads[0] / self::getNumberOfProcessorCores() );
		$class			= "info";
		if( $load0Relative < 0.9 )
			$class		= "success";
		if( $load0Relative < 0.6 )
			$class		= "warning";
		if( $load0Relative < 0.3 )
			$class		= "danger";
		$bar		= UI_HTML_Tag::create( 'div', "", array(
			'class'	=> 'bar bar-'.$class,
			'style' => 'width: '.round( $load0Relative * 100, 3 ).'%'
		) );
		return UI_HTML_Tag::create( 'div', $bar, array( 'class' => 'progress' ) );
	}
}
?>

